<!DOCTYPE html>
<html>
<head>
<title>Click Collapsible Task</title>
<!-- stylesheets -->
<link rel="stylesheet" type="text/css" href="../core/core.css">
<!-- JS -->
<script src="../core/core.js"></script>
<script src="../core/d3.v3.min.js"></script>
<script src="../core/jquery-ui/external/jquery/jquery.js"></script>
<script src="../core/jquery-ui/jquery-ui.min.js"></script>
<script src="../common/ui_utils.js"></script>

<style>
#area h3 { background: #007fff; border: 1px solid #003eff; border-radius: 3px; color: #ffffff; font-weight: normal; margin: 2px; padding: 1px; }
#area div { margin: 2px; }
.alink { text-decoration: underline; color: blue; cursor: pointer; }
.ui-accordion-content { border-width: 0 1px 1px 1px; border-style: solid; padding: 1px; }
</style>

<script>
var createLinks = function(div){
  for(var i=0;i<3;i++){
    var header = '<h3> Section #' + (i+1) + '</h3>';
    var txt =  ui_utils.generateWords(20).split(/\s/g);
    for(var j=0;j<txt.length; j++){
      if(Math.random() < 0.2) txt[j] = '<span class="alink">' + txt[j] + '</span>';
    }
    html = '<div>' + txt.join(' '); + '</div>';

    // place in DOM
    div.append(header + html);
  }
}

var bindClickEvents = function(){
  // now hook handlers to all generated links
  var elements = document.getElementsByClassName('alink');
  var correct_ix = core.randi(0, elements.length);
  var correct_text = elements[correct_ix].innerHTML;

  for(var i = 0, len = elements.length; i < len; i++) {
    var e = elements[i];
    if(e.innerHTML === correct_text) {
      d3.select(e).on('click', function(){ core.endEpisode(1.0, true); })
    } else {
      d3.select(e).on('click', function(){ core.endEpisode(-1.0); })
    }
  }
  return elements[correct_ix].innerHTML;
}

var genProblem = function() {
  // generate the task
  var div = $('#area');
  if(div.html().length > 0){ $('#area').accordion('destroy'); }
  div.empty(); // clear previous problem, if any

  createLinks(div);
  var any = core.getOpt(core.QueryString, 'any', false); // click any link?
  var correctText = bindClickEvents();

  // generate query text in the UI
  d3.select('#query').html('Expand the sections below, to find and click on the link "' + correctText + '".');
  $('#area').accordion({active: false, collapsible: true});
}

window.onload = function() {
  core.startEpisode();
}
</script>
</head>
<body>
<div id="wrap">
  <div id="query"></div>
  <div id="area"></div>
</div>
</body>
</html>
